package com.fingard.dsp.bank.directbank.alipay01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQRPay;
import com.fingard.dsp.bank.reqrespobj.qrpay.ReqGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.qrpay.RetAtsGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;

import net.sf.json.JSONObject;

public class ALIPAY01QRPay extends ALIPAY01Base implements IQRPay {
	public RetAtsGenQRInfo genQRInfo(ReqGenQRInfo p_req) {
		RetAtsGenQRInfo retAts = new RetAtsGenQRInfo();
		
		retAts.rdSeq = p_req.rdSeq;
		retAts.respCode = "0";
		retAts.respInfo = "暂不支持此接口:" + p_req.reqHeader.transType;
		retAts.qrInfo = "";
		
		return retAts;
	}

	public RetAtsUnifiedOrder submitQROrder(ReqUnifiedOrder p_req) {
		RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
		retAts.rdSeq = p_req.rdSeq;
		
		try {
			logIsExist();
			
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
			if (actItem != null) {
				JSONObject alipayJsonRequest = new JSONObject();
				alipayJsonRequest.put("out_trade_no", p_req.rdSeq);
				alipayJsonRequest.put("timeout_express", getValidTime(p_req.getValidTime()));
				alipayJsonRequest.put("total_amount", p_req.amount);
				alipayJsonRequest.put("body", XmlHelper.encode(p_req.attach));
				alipayJsonRequest.put("subject", XmlHelper.encode(p_req.description));

				String enable_pay_channels = getBankConfig().getValueAsString("enablePayChannels");
				if(!StringHelper.isNullOrEmpty(enable_pay_channels)){
					alipayJsonRequest.put("enable_pay_channels", enable_pay_channels);
				}
				
				if(StringHelper.hasAnyChar(p_req.insureAreaCode) || StringHelper.hasAnyChar(p_req.sHTradeNo)) {
					StringBuilder insuranceMsg = new StringBuilder();
					insuranceMsg.append("\"{\\\"insuranceFlag\":\"T\"," +
							"\"insureAreaCode\":\""+p_req.insureAreaCode+"\"," +
							"\"insuranceType\":\"alipay_auto_ins\",\"shTradeNo\":\""+p_req.sHTradeNo+"\"}\"");
					JSONObject insuranceInfo = new JSONObject();
					insuranceInfo.put("insurance_info", insuranceMsg.toString());
					alipayJsonRequest.put("extend_params", insuranceInfo);
				}
				
				AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
                String authFlag = "F";
                if ("1".equals(p_req.realNameFlag)) {
                    authFlag = "T";
                } else if ("0".equals(p_req.realNameFlag)) {
                    authFlag = "F";
                } else {
                    if (StringHelper.hasAnyChar(p_req.oppActName) || StringHelper.hasAnyChar(p_req.certNumber) || StringHelper.hasAnyChar(p_req.cellPhone)) {
                        authFlag = "T";
                    }
                }
                JSONObject userInfoJson = new JSONObject();
                userInfoJson.put("name", p_req.oppActName);
                userInfoJson.put("mobile", p_req.cellPhone);
                userInfoJson.put("cert_type", convertCertTypeToBank(p_req.certType));
                userInfoJson.put("cert_no", p_req.certNumber);
                userInfoJson.put("need_check_info", authFlag);
                if ("T".equals(authFlag)) {
                    alipayJsonRequest.put("ext_user_info", userInfoJson);
                }

                String bizContent = JSON.toJSONString(alipayJsonRequest);
				bizContent = bizContent.replaceAll("\\\\\\\\", "");
				request.setBizContent(bizContent);
				
				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(request.getBizContent());

				String signType = "RSA2";
            	boolean useSignType = getBankConfig().getValueAsBool("useSignType");
            	if (useSignType) {
            		signType = actItem.signType;
            	}

                request.setNotifyUrl(actItem.notifyURL);

                AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId,
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);
				
				AlipayTradePrecreateResponse response = alipayClient.execute(request);
				WriteBankLogStep3(response.getBody());
				
				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				retAts.qrInfo = response.getQrCode();
				if (!"10000".equals(response.getCode())) {
					retAts.respCode = "-1";
					retAts.respInfo = response.getSubMsg();
					retAts.qrInfo = "";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
				retAts.qrInfo = "";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}
	
	public RetAtsQueryOrder queryQRPay(ReqQueryOrder p_req) {
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
		retAts.rdSeq = p_req.rdSeq;
		
		try {
			logIsExist();
			
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if (actItem != null) {
				AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
				request.setBizContent("{\"out_trade_no\":\"" + p_req.rdSeq +"\"}");
				
				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(request.getBizContent());
				
				String signType = "RSA2";
            	boolean useSignType = getBankConfig().getValueAsBool("useSignType");
            	if (useSignType) {
            		signType = actItem.signType;
            	}
				
				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, 
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);
				
				AlipayTradeQueryResponse response = alipayClient.execute(request);
				WriteBankLogStep3(response.getBody());
				
				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				if ("10000".equals(response.getCode())) {
					retAts.transState = StringHelper.joinNotEmpty("+", response.getCode(), response.getTradeStatus());
					retAts.payInfoCode = response.getTradeStatus();
					retAts.outTransID = response.getTradeNo();
					retAts.openId = response.getOpenId();
					retAts.oppAct = response.getBuyerLogonId();
				} else {
					retAts.transState = StringHelper.joinNotEmpty("+", response.getCode(), response.getSubCode());
					retAts.payInfoCode = response.getSubCode();
					retAts.respInfo = response.getSubMsg();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}
}
